package com.liu.aidlclient;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.liu.aidlserver.IMyService;
import com.liu.aidlserver.Student;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void open(View view){
        Intent intentService = new Intent("com.ryg.sayhi.MyService");
        intentService.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        MainActivity.this.bindService(intentService, mServiceConnection, BIND_AUTO_CREATE);
    }

    private IMyService myService;
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myService = IMyService.Stub.asInterface(service);
            try {
                Student student = myService.getStudent().get(0);
                showDialog(student.toString());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            myService = null;
        }
    };

    private void showDialog(String s) {
        new AlertDialog.Builder(MainActivity.this)
                .setTitle("scott")
                .setMessage(s)
                .setPositiveButton("确定", null)
                .show();
    }
}
